package com.bole.service.impl;

import com.bole.dao.AdminRoleDao;
import com.bole.dao.MenuRoleDao;
import com.bole.dao.RoleDao;
import com.bole.pojo.AdminRoleDo;
import com.bole.pojo.MenuRoleDo;
import com.bole.pojo.TbRoleDo;
import com.bole.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yakamaxi
 * @version 1.0
 * @date 2020/8/12 13:54
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AdminRoleDao adminRoleDao;
    @Autowired
    private MenuRoleDao menuRoleDao;

    @Override
    public List<TbRoleDo> getInfo() {
        return roleDao.findAll();
    }

    @Override
    public void add(TbRoleDo roleDo, Long[] nodeIds) {
        roleDao.save(roleDo);

        ArrayList<MenuRoleDo> menuRoleDos = new ArrayList<>();
        for (Long nodeId : nodeIds) {
            //  增加中间表
            MenuRoleDo menuRoleDo = new MenuRoleDo();
            // 设置角色 id
            menuRoleDo.setRoleId(roleDo.getId());
            menuRoleDo.setMenuId(nodeId);
            menuRoleDos.add(menuRoleDo);
            //  🤡
        }
        menuRoleDao.saveAll(menuRoleDos);
    }

    @Override
    public TbRoleDo getRoleById(Long id) {
        return roleDao.findTbRoleDoById(id);
    }

    @Override
    public void updateById(TbRoleDo roleDo, Long[] nodeIds) {
        roleDao.save(roleDo);
        // 先删除中间表数据 (先查)
        List<MenuRoleDo> menuRoleDoByRoleId = menuRoleDao.findMenuRoleDoByRoleId(roleDo.getId());
        menuRoleDao.deleteAll(menuRoleDoByRoleId);
        ArrayList<MenuRoleDo> menuRoleDos = new ArrayList<>();
        // 增加中间表数据
        for (Long nodeId : nodeIds) {
            MenuRoleDo menuRoleDo = new MenuRoleDo();
            menuRoleDo.setRoleId(roleDo.getId());
            menuRoleDo.setMenuId(nodeId);
            menuRoleDos.add(menuRoleDo);
        }
        menuRoleDao.saveAll(menuRoleDos);
    }

    @Override
    public void deleteById(Long id) {
        // 删除角色数据
        roleDao.deleteById(id);
        // 还要删除中间表数据
        List<MenuRoleDo> menuRoleDoByRoleId = menuRoleDao.findMenuRoleDoByRoleId(id);
        menuRoleDao.deleteAll(menuRoleDoByRoleId);
    }

    // 根据用户查询对应角色 的 id
    @Override
    public Long findRoleByAdminId(Long id) {
        //        List<Long> list = new ArrayList<>();
//        byAdminId.forEach(x -> list.add(x.getRoleId()));
        return adminRoleDao.findRoleByAdminId(id);
    }

}
